import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import { calculatePrice, setCart, getCart } from '../utils';
import { Text, Button, Heading, Box, Image, Card, Mask, IconButton } from 'gestalt';
import Strapi from 'strapi-sdk-javascript/build/main';
const apiUrl = process.env.API_URL || 'http://localhost:1337';
const strapi = new Strapi(apiUrl);

class Brews extends Component {
  state = {
    brews: [],
    brand: '',
    cartItems: [],
  }

  async componentDidMount() {
    try {
      const brandId = this.props.match.params.id;
      const res = await strapi.request('POST', '/graphql', {
        data: {
          query: `
        query {
          brand(id: "${brandId}") {
            id
            name
            brews {
              id
              name
              descrition
              image {
                url
              }
              price
            }
          }
        }`
        }
      });
      const { data } = res;
      this.setState({
        brews: data.brand.brews,
        brand: data.brand.name,
        cartItems: getCart()
      });
    } catch (error) {
      console.error(error);
    }
  }

  handleAddCart = brew => {
    const hasInCart = this.state.cartItems.findIndex(item => item.id === brew.id);
    if (hasInCart === -1) {
      const updatedItems = this.state.cartItems.concat({
        ...brew,
        qty: 1
      });
      this.setState({ cartItems: updatedItems }, () => setCart(updatedItems))
    } else {
      const updatedItems = [...this.state.cartItems];
      updatedItems[hasInCart].qty += 1;
      this.setState({ cartItems: updatedItems }, () => setCart(updatedItems));
    }
  }

  handleDeleteItemFromCart = id => {
    const filteredItems = this.state.cartItems.filter(item => item.id !== id);
    this.setState({ cartItems: filteredItems }, () => setCart(filteredItems));
  }

  render() {
    const { brand, brews, cartItems } = this.state;
    return (
      <Box
        marginTop={4}
        display='flex'
        alignItems="start"
        justifyContent="center"
        dangerouslySetInlineStyle={{
          __style: {
            flexWrap: 'wrap-reverse'
          }
        }}
      >
        {/* Brews Section */}
        <Box
          display='flex'
          direction='column'
          alignItems='center'
        >
          <Box margin={2}>
            {/* Brew Heading */}
            <Heading color="orchid">{brand}</Heading>
          </Box>
          <Box
            dangerouslySetInlineStyle={{
              __style: {
                backgroundColor: '#dbcdd9'
              }
            }}
            shape="rounded"
            display="flex"
            justifyContent='center'
            padding={4}
          >
            {brews.map(brew => (
              <Box
                paddingY={4}
                margin={2}
                width={220}
                key={brew.id}
              >
                <Card
                  image={
                    <Box height={250} width={200}>
                      <Image fit="cover" alt="brew" naturalHeight={1} naturalWidth={1} src={`${apiUrl}${brew.image.url}`}></Image>
                    </Box>
                  }
                >
                  <Box
                    display="flex"
                    alignItems="center"
                    justifyContent="center"
                    direction="column"
                  >
                    <Box marginBottom={2}>
                      <Text blod text size="xl">{brew.name}</Text>
                    </Box>
                    <Text text size="xl">{brew.descrition}</Text>
                    <Text color='orchid' size="xl">${brew.price}</Text>
                    <Box marginTop={2}>
                      <Text blod text size="xl">
                        <Button onClick={this.handleAddCart.bind(this, brew)} color='blue' text='Add To Cart' />
                      </Text>
                    </Box>
                  </Box>
                </Card>
              </Box>
            ))}
          </Box>
        </Box>

        {/* User Cart */}
        <Box alignSelf='end' marginTop={2} marginLeft={8}>
          <Mask shape='rounded' wash>
            <Box display='flex' direction='column' alignItems='center' padding={2}>
              {/* User Cart Heading */}
              <Heading align='center' size='sm'>Your Cart</Heading>
              <Text color='gray' italic >{cartItems.length || 0} items selected</Text>

              {/* Cart Item */}
              {cartItems.map(item => (
                <Box key={item.id} display='flex' alignItems='center'>
                  <Text>
                    {item.name} x {item.qty} = ${(item.qty * item.price).toFixed(2)}
                  </Text>
                  <IconButton
                    accessibilityLabel='Delete Item'
                    icon='cancel'
                    size='sm'
                    iconColor='red'
                    onClick={() => this.handleDeleteItemFromCart(item.id)}
                  />
                </Box>
              ))}


              <Box display='flex' alignItems='center' justifyContent='center' direction='column'>
                <Box margin={2}>
                  {cartItems.length === 0 && (
                    <Text color='red'>Please select some item</Text>
                  )}
                </Box>
                <Text size='lg'>Total: {calculatePrice(cartItems)}</Text>
                <Text>
                  <Link to='/checkout'>Checkout</Link>
                </Text>
              </Box>
            </Box>
          </Mask>
        </Box>
      </Box>
    )
  }
}

export default Brews;